<template>
	<view class="container">
		<!--地图-->
		<view 
			id="amap" 
			:latlon="latlon" :change:latlon="amap.updateLatlon" 
			:beginLatlon="beginLatlon" :change:beginLatlon="amap.updateBeginLatlon" 
			:targetLatlon="targetLatlon" :change:targetLatlon="amap.updateTargetLatlon"
		>
		</view>
		<!--定位图标-->
		<view class="location" @click="getLocation">
			<uni-icons type="map-pin-ellipse" color="#fff" size="25"></uni-icons>
		</view>
		<!--订单卡片-->
		<view class="box">
			<view class="head">
				<view class="avatar">
					<image :src="getUserAvatarOrDefault(info.avatar)" alt="avatar" />
				</view>
				<view class="center">
					<view class="username">
						{{ info.username }}
					</view>
					<view class="xcx">
						小程序
					</view>
				</view>
				<view class="call" @tap="callClient">
					<uni-icons type="phone" size="26" color="#19afff"></uni-icons>
				</view>
			</view>
			<view class="tags">
				<view>
					实时
				</view>
				<view>
					里程模式
				</view>
				<view>
					距您:{{ info.distanceNonStraight }}km
				</view>
				<view class="price" v-if="orderTypeEnum.FINISH.code !== info.status">
					<text>预计: </text>
					<text class="num">{{ formatAmount(info.price) }}</text>
					<text>(元)</text>
				</view>
			</view>
			<view class="from-and-to">
				<view class="from">
					<view class="left">
						<view class="dot green"></view>
						<view class="text">起点：{{ info.currentAddr }}</view>
					</view>
					<view class="right" @tap="handlerGotoAddr('start')">
						<text>导航</text>
						<uni-icons type="right" color="#19afff"></uni-icons>
					</view>
				</view>
				<view class="to">
					<view class="left">
						<view class="dot red"></view>
						<view class="text">终点：{{ info.targetAddr }}</view>
					</view>
					<view class="right" @tap="handlerGotoAddr('end')">
						<text>导航</text>
						<uni-icons type="right" color="#19afff"></uni-icons>
					</view>
				</view>
			</view>
			<view class="time">
				<view>
					订单号：{{ info.id }}
				</view>
				<view>
					下单时间：{{ formatDatetime(info.orderTime) }}
				</view>
				<view>
					出发时间：{{ formatDatetime(info.hopeTime) }}
				</view>
				<view v-if="[orderTypeEnum.PENDING_PAY.code, orderTypeEnum.FINISH.code].includes(info.status) && info.endTime">
					到达时间：{{ formatDatetime(info.endTime) }}
				</view>
			</view>
			<!--按钮-->
			<view class="btn-contanier">
				<view class="btn primary-btn" @tap="handlerGrabOrder" v-if="orderTypeEnum.WAIT.code === info.status">
					迅速抢单
				</view>
				
				<!-- <view class="btn-cancel" @tap="handlerCancelOrder" v-if="[orderTypeEnum.GET.code, orderTypeEnum.WAITING.code].includes(info.status)">
					取消订单
				</view> -->
				
				<view 
					class="btn-goto primary-btn" 
					v-if="[orderTypeEnum.GET.code, orderTypeEnum.WAITING.code, orderTypeEnum.START.code].includes(info.status)"
					@tap="handlerUpdateOrderStatus(info.status + 1, status2text(info.status))"
				>
					{{ status2text(info.status) }}
				</view>
			</view>
		</view>
		
	</view>
</template>

<script>
import { ref, nextTick, reactive, onUnmounted } from "vue"
import { onShow, onLoad } from "@dcloudio/uni-app"
import { grabOrder, cancelOrder, updateStatus, finishOrder } from '@/api/order.js'
import { orderTypeEnum } from '@/utils/orderType.js'
import { formatDatetime } from '@/utils/datetimeUtil.js'
import { useUserStore } from '@/stores/userStore.js'
import { formatAmount } from '@/utils/amountUtil.js'
import { getUserAvatarOrDefault } from '@/utils/imageUtil.js'
// #ifdef APP-PLUS
import recorderManager from "@/utils/recorderManager"
// #endif

export default {
	setup() {
		const driver = useUserStore()
		// 当前位置
		const latlon = ref({
			latitude: 39.908823,
			longitude: 116.39747
		})
		// 出发位置
		const beginLatlon = ref({
			latitude: 39.908823,
			longitude: 116.39747
		})
		// 目标位置
		const targetLatlon = ref({
			latitude: 39.908823,
			longitude: 116.39747
		})
		// 订单信息
		const info = ref({
			id: null,
			businessType: null,
			currentLo: null,
			currentLa: null,
			currentAddr: null,
			targetLo: null,
			targetLa: null,
			targetAddr: null,
			orderTime: null,
			hopeTime: null,
			receiveTime: null,
			reachTime: null,
			startTime: null,
			endTime: null,
			price: null,
			userId: null,
			username: null,
			avatar: null,
			userPhone: null,
			status: null,
			remark: null,
			driverId: null,
			driverAge: null,
			surname: null,
			name: null,
			driverPhone: null,
			driverStatus: null
		})
		// 录音是否播放中
		const playingRecord = ref(false)
		
		/** 根据状态返回文字 */
		function status2text (status) {
			switch (status) {
				case orderTypeEnum.GET.code:
					return '开始等待'
				case orderTypeEnum.WAITING.code:
					return '开始服务'
				case orderTypeEnum.START.code:
					return '完成订单'
			}
		}
		
		/** 获取定位 */
		function getLocation () {
			return new Promise((resolve, reject) => {
				// 浏览器
				// #ifndef APP-PLUS
				 //h5无法使用uni定位所以传入固定的坐标
				latlon.value.latitude = 39.908823
				latlon.value.longitude = 116.39747
				resolve()
				// #endif
				
				// APP
				// #ifdef APP-PLUS
				uni.showLoading({
					title: '获取定位中...'
				})
				uni.getLocation({
					type: 'gcj02',
					isHighAccuracy: true,
					success: function(res) {
						// 当前位置
						latlon.value.latitude = res.latitude
						latlon.value.longitude = res.longitude
						resolve()
					},
					fail: function(err) {
						console.error('获取位置信息失败')
						reject(err)
					},
					complete: function(e) {
						uni.hideLoading()
					}
				})
				// #endif
			})
		}
		
		/** 呼叫用户 */
		function callClient () {
			console.log(info.value.userPhone)
			uni.makePhoneCall({
				phoneNumber: info.value.userPhone
			})
		}
		
		/** 抢单 */
		function handlerGrabOrder () {
			grabOrder(info.value.id).then(() => {
				uni.showToast({
					icon: 'none',
					title: '抢单成功'
				})
				info.value.status = 2
			})
		}
		/** 取消订单 */
		function handlerCancelOrder () {
			uni.showModal({
				title: '提示',
				content: `确定要取消订单吗？`,
				success: (res) => {
					if (res.confirm) {
						// 取消订单
						cancelOrder(info.value.id).then(() => {
							uni.showToast({
								title: '已取消',
								icon: 'none'
							})
							setTimeout(() => {
								uni.$emit('reload-order-list')
								uni.navigateBack()
							}, 500)
						})
					}
				}
			})
		}
		/** 开始等待 或 开始服务 或 确认送达 */
		function handlerUpdateOrderStatus (status, msg) {
			uni.showModal({
				title: '提示',
				content: `确定要${msg}吗？`,
				success: (res) => {
					if (res.confirm) {
						if (status === orderTypeEnum.PENDING_PAY.code) {
							// 如果是司机点击“完成订单”，那么传过来这个status就是待支付，需要司机选择用户的支付方式
							uni.showActionSheet({
								title: '请选择用户的支付方式',
								itemList: ['小程序线上支付', '扫码支付', '现金支付'],
								success: function (res) {
									finishOrder({ orderId: info.value.id, payType: res.tapIndex }).then(res => {
										uni.showToast({
											title: '操作成功',
											icon: 'none',
											success: () => {
												uni.reLaunch({
													url: '/pages/order/order'
												})
											}
										})
									})
								},
								fail: function (res) {
									console.log(res.errMsg);
								}
							});
						} else {
							// 其他操作，直接更新状态即可
							updateStatus({ id: info.value.id, status }).then(res => {
								info.value.status = status
								uni.showToast({
									icon: 'none',
									title: '操作成功'
								})
							})
						}
						
						// 录音
						// #ifdef APP-PLUS
						if (orderTypeEnum.START.code === status) {
							recorderManager.setCurrentOrderId(info.value.id)
							recorderManager.startRecord()
						} else if (orderTypeEnum.PENDING_PAY.code === status) {
							recorderManager.endRecord()
						}
						// #endif
					}
				}
			})
			
		}
		
		/** 更新距离 */
		function updateDistance (distance) {
			info.value.distanceNonStraight = distance
		}
		
		/** 去起点或终点 */
		function handlerGotoAddr (where) {
			const name = where === 'start' ? info.value.currentAddr : info.value.targetAddr
			const lat = where === 'start' ? info.value.currentLa : info.value.targetLa
			const lon = where === 'start' ? info.value.currentLo : info.value.targetLo
			let url = `androidamap://viewMap?sourceApplication=appname&poiname=${name}&lat=${lat}&lon=${lon}&dev=0`
			if (plus.os.name == "Android") { // 安卓
				url = `androidamap://viewMap?sourceApplication=appname&poiname=${name}&lat=${lat}&lon=${lon}&dev=0`
			} else { //苹果
				url = `iosamap://viewMap?sourceApplication=applicationName&poiname=${name}&lat=${lat}&lon=${lon}&dev=0`
			}
			url = encodeURI(url)
			plus.runtime.openURL(url, (err) => {
				uni.showModal({
					title: '提示',
					content: '检测到您本机暂未安装高德地图应用，是否要选择使用浏览器打开？',
					success: function(res) {
						if (res.confirm) {
							let webUrl = `https://uri.amap.com/marker?position=${lon},${lat}&name=${name}&src=mypage&coordinate=gaode`
							plus.runtime.openURL(webUrl)
						}
					}
				})
			})
		}
		
		/** 初始化位置 */
		function initLocation () {
			getLocation().then(res => {
				nextTick(() => {
					if (info.value.status === orderTypeEnum.WAIT.code) {
						// 如果是待接单，展示 司机当前位置 到 用户出发位置
						beginLatlon.value = latlon.value
						targetLatlon.value.latitude = info.value.currentLa
						targetLatlon.value.longitude = info.value.currentLo
					} else {
						// 否则展示 用户起点 到 用户终点
						beginLatlon.value.latitude = info.value.currentLa
						beginLatlon.value.longitude = info.value.currentLo
						targetLatlon.value.latitude = info.value.targetLa
						targetLatlon.value.longitude = info.value.targetLo
					}
				})
			})
		}
		
		/** 页面挂载 */
		onLoad(e => {
			const query = JSON.parse(e.query)
			// console.log(query)
			info.value = query
			// 初始化位置
			initLocation()
			
			// #ifdef APP-PLUS
			// 监听录音暂停或播放完
			recorderManager.innerAudioContext.onPause(res => {
				playingRecord.value = false
			})
			// #endif
		})
		
		return {
			latlon,
			beginLatlon,
			targetLatlon,
			info,
			status2text,
			getLocation,
			callClient,
			handlerGrabOrder,
			handlerCancelOrder,
			orderTypeEnum,
			formatDatetime,
			updateDistance,
			handlerGotoAddr,
			handlerUpdateOrderStatus,
			playingRecord,
			formatAmount,
			getUserAvatarOrDefault
		}
	}
}

</script>

<script lang="renderjs" module="amap">
// #ifdef APP-PLUS
window._AMapSecurityConfig = {
	securityJsCode: "fee7883c1566f61f68569bf2c81bb259"
};
// #endif
import AMapLoader from '@vuemap/amap-jsapi-loader';
// import AMapLoader from "@amap/amap-jsapi-loader";

export default {
	data() {
		return {
			ownerInstanceObj: null,
			map: null,
			latlon: {
				latitude: 39.908823,
				longitude: 116.39747
			},
			beginLatlon: {
				latitude: 39.908823,
				longitude: 116.39747
			},
			targetLatlon: {
				latitude: 39.908823,
				longitude: 116.39747
			}
		}
	},
	methods: {
		/** 判断出发位置是否变化了 */
		beginHasChanged() {
			return this.beginLatlon.latitude !== 39.908823 || this.beginLatlon.longitude !== 116.39747
		},
		/** 判断目的地位置是否变化了 */
		targetHasChanged() {
			return this.targetLatlon.latitude !== 39.908823 || this.targetLatlon.longitude !== 116.39747
		},
		/** 初始化 */
		init() {
			return new Promise((resolve, reject) => {
				AMapLoader.load({
					// #ifdef APP-PLUS
					key: "51097d93f1ba672d7eff74764c29685c",
					// #endif
					// #ifndef APP-PLUS
					key: "9996b2ae4c2bd5c1caab3861243bb047",
					// #endif
					version: "2.0", 						   // 默认1.4.15
					plugins: ['AMap.Driving', 'AMap.ToolBar'], 
					AMapUI: {
						version: '1.1',
						plugins: ['overlay/SimpleMarker'],
					},
					Loca: {
						version: '2.0'
					}
				}).then(AMap => {
					resolve(AMap)
				}).catch(err => {
					console.error(err)
					reject(err)
				})
			})
		},
		/** 加载地图和路线 */
		initMap() {
			if (!this.beginHasChanged() || !this.targetHasChanged()) {
				return
			}
			this.init().then(AMap => {
				// map
				this.map = new AMap.Map('amap', {
					center: new AMap.LngLat(this.latlon.longitude, this.latlon.latitude),
					showLabel: true,
					resizeEnable: true,
					viewMode: '3D',
					zoom: 12 //地图显示的缩放级别
				})
				// this.map.addControl(new AMap.ToolBar())
				// driver
				const driving = new AMap.Driving({
					map: this.map,
				})
				const that = this
				// 根据起终点经纬度规划驾车导航路线
				driving.search(new AMap.LngLat(this.beginLatlon.longitude, this.beginLatlon.latitude), new AMap.LngLat(this.targetLatlon.longitude, this.targetLatlon.latitude),
					function(status, result) {
						if (status === 'complete') {
							if (that.ownerInstanceObj) {
								that.ownerInstanceObj.callMethod('updateDistance', (result.routes[0].distance / 1000).toFixed(2))
							}
							// console.log(JSON.stringify(result))
						} else {
							console.error('获取驾车数据失败: ' + JSON.stringify(result))
						}
					}
				)
			})
		},
		
		//监听逻辑层传递过来的经纬度
		updateLatlon(nv, ov) {
			this.latlon = nv
		},
		updateBeginLatlon(nv, ov) {
			this.beginLatlon = nv
			this.initMap()
		},
		updateTargetLatlon(nv, ov, ownerInstance) {
			this.ownerInstanceObj = ownerInstance
			this.targetLatlon = nv
			this.initMap()
		}
	}

}
</script>

<style lang="scss" scoped>
view {
	box-sizing: border-box;
}
.container {
	width: 100vw;
	height: 100vh;
	position: relative;
	
	#amap {
		width: 100%;
		height: 60%;
	}
	
	.location {
		width: 35px;
		height: 35px;
		background: #0079FE;
		display: flex;
		justify-content: center;
		border-radius: 50%;
		align-items: center;
		position: absolute;
		bottom: calc(40% + 80rpx);
		right: 30rpx;
		z-index: 55;
	}
	
	.box {
		width: 100%;
		bottom: 60rpx;
		height: calc(40% + 60rpx);
		position: relative;
		
		background-color: #fff;
		padding: 30rpx;
		z-index: 99999;
		border-radius: 30rpx 30rpx 0 0;
		
		display: flex;
		flex-direction: column;
		
		.head {
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: space-between;
			.avatar {
				width: 100rpx;
				height: 100rpx;
				border-radius: 50%;
				overflow: hidden;
				display: flex;
				align-items: center;
				justify-content: center;
				image {
					width: 100%;
					height: 100%;
					object-fit: cover;
				}
			}
			.center {
				flex: 1;
				padding: 0 30rpx;
				.username {
					font-size: 32rpx;
					font-weight: 600;
					margin-bottom: 6rpx;
				}
				.xcx {
					font-size: 22rpx;
					color: #555;
				}
			}
			.call {
				
			}
		}
	
		.tags {
			display: flex;
			align-items: center;
			color: #555;
			font-size: 26rpx;
			padding: 20rpx 0;
			&>view {
				margin-right: 20rpx;
			}
			.price {
				font-size: 26rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				.num {
					font-size: 34rpx;
					font-weight: 600;
					color: #e00;
				}
			}
		}
		
		.from-and-to {
			.from, .to {
				width: 100%;
				margin-bottom: 20rpx;
				font-size: 28rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;
				
				.left {
					display: flex;
					align-items: center;
					justify-content: flex-start;
					
					.dot {
						width: 18rpx;
						height: 18rpx;
						border-radius: 50%;
						margin-right: 15rpx;
					}
					.green {
						background-color: #00b400;
					}
					.red {
						background-color: #d60000;
					}
					.text {
						white-space: nowrap;
						overflow: hidden;
						text-overflow: ellipsis;
						width: 540rpx;
					}
				}
				
				.right {
					width: 100rpx;
					display: flex;
					align-items: center;
					justify-content: flex-end;
					color: #19afff;
				}
				
			}
			.from {
			}
			.to {
			}
		}
	
		.time {
			&>view {
				margin-bottom: 20rpx;
				font-size: 28rpx;
				// color: #555;
			}
		}
	
		.btn-contanier {
			background-color: #fff;
			flex: 1;
			display: flex;
			align-items: flex-end;
			justify-content: space-between;
			&>view {
				text-align: center;
				padding: 30rpx 0;
				border-radius: 15rpx;
				color: #fff;
				transition: all 0.3s ease;
			}
			.btn {
				width: 100%;
			}
			.btn-cancel {
				width: 40%;
				margin-right: 30rpx;
			}
			.btn-goto {
				flex: 1;
			}
			
		}
	
	}
}
</style>
